package cn.yunyichina.provider.sb.service.impl;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.hisiface.shangbao.SBInPatientDiagnosisVo;
import cn.yunyichina.provider.iface.entity.hisiface.shangbao.SBInPatientDiagnosisVoResponse;
import cn.yunyichina.provider.sb.constant.Constant;
import cn.yunyichina.provider.sb.dao.MedicalInhospitalDiagnosisDao;
import cn.yunyichina.provider.sb.dao.MedicalPatientDao;
import cn.yunyichina.provider.sb.entity.MedicalInhospitalDiagnosis;
import cn.yunyichina.provider.sb.entity.MedicalPatient;
import cn.yunyichina.provider.sb.util.Util;
import cn.yunyichina.provider.sb.vo.MedicalInhospitalDiagnosisVo;
import cn.yunyichina.provider.sb.vo.SbRequest;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alipay.api.response.AlipayCommerceDataSendResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * Created by 15-AK on 2017/7/25.
 */
public class InhospitalDiagnosisServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(InhospitalDiagnosisServiceImpl.class);
    private MedicalInhospitalDiagnosisDao medicalInhospitalDiagnosisDao = SpringContextHandler.getBean("medicalInhospitalDiagnosisDao");
    private MedicalPatientDao medicalPatientDao = SpringContextHandler.getBean("medicalPatientDao");

    private final static String HOSPITAL_CODE = "szszyy";

    public void executeUploadInhospitalDiagnosis() {
        try {
            MedicalInhospitalDiagnosis queryMedicalInhospitalDiagnosis = new MedicalInhospitalDiagnosis();
            queryMedicalInhospitalDiagnosis.setUploadFlag(new Short("0"));
            queryMedicalInhospitalDiagnosis.setOrgCode(HOSPITAL_CODE);
            List<MedicalInhospitalDiagnosis> medicalInhospitalDiagnosisList = medicalInhospitalDiagnosisDao.selectNoUploadData(queryMedicalInhospitalDiagnosis);
            if (CollectionUtils.isNotEmpty(medicalInhospitalDiagnosisList)) {
                for (MedicalInhospitalDiagnosis medicalInhospitalDiagnosis : medicalInhospitalDiagnosisList) {
                    logger.info("inPatientId ={},待上传住院诊断信息medicalInhospitalDiagnosis={}", new Object[]{medicalInhospitalDiagnosis.getInpatientId(),JsonUtils.toJsonString(medicalInhospitalDiagnosis)});
                    MedicalInhospitalDiagnosisVo medicalInhospitalDiagnosisVo = new MedicalInhospitalDiagnosisVo();
                    String encryptData = Util.encryptMedicalInhospitalDiagnosisVo(medicalInhospitalDiagnosisVo.buildMedicalInhospitalDiagnosisVo(medicalInhospitalDiagnosis), Constant.ENCRYPT_KEY);
                    SbRequest sbRequest = new SbRequest();
                    sbRequest.setSceneCode(Constant.MEDICAL_INHOSPITAL_DIAGNOSIS);
                    sbRequest.setEncryptData(encryptData);
                    try {
                        AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                        logger.info("inPatientId ={},住院诊断信息上传支付宝响应参数response={}", new Object[]{JsonUtils.toJsonString(response)});
                        if (response.isSuccess()) {
                            logger.info("inPatientId ={}住院诊断信息上传成功",medicalInhospitalDiagnosis.getInpatientId());
                            medicalInhospitalDiagnosis.setUploadFlag(new Short("1"));
                        } else {
                            logger.info("inPatientId ={}住院诊断信息上传失败",medicalInhospitalDiagnosis.getInpatientId());
                            medicalInhospitalDiagnosis.setExceptionMessage(response.getSubMsg());
                        }
                        medicalInhospitalDiagnosis.setUploadTimes(medicalInhospitalDiagnosis.getUploadTimes() + 1);
                        medicalInhospitalDiagnosisDao.update(medicalInhospitalDiagnosis);
                    } catch (Exception e) {
                        logger.error("住院诊断信息上传系统异常", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("住院诊断信息上传系统异常", e);
        }
    }


    public void executeDownloadInhospitalDiagnosis() {
        MedicalPatient queryMedicalPatient = new MedicalPatient();
        queryMedicalPatient.setOrgCode(HOSPITAL_CODE);
        queryMedicalPatient.setBusinessType(new Short("2"));
        queryMedicalPatient.setOutHospitalNotityFlag(new Short("1"));
        queryMedicalPatient.setDownLoadDiagnosisFlag(new Short("0"));
        queryMedicalPatient.setNotifyFlag(new Short("1"));
        List<MedicalPatient> medicalPatientList = medicalPatientDao.select(queryMedicalPatient);
        if (CollectionUtils.isNotEmpty(medicalPatientList)) {
            for (MedicalPatient medicalPatient : medicalPatientList) {
                logger.info("inPatientId ={},待下载住院诊断信息就诊人信息medicalPatient={}", new Object[]{medicalPatient.getInpatientId(),JsonUtils.toJsonString(medicalPatient)});
                SBInPatientDiagnosisVo inPatientDiagnosisVo = new SBInPatientDiagnosisVo();
                inPatientDiagnosisVo.setInPatientId(medicalPatient.getInpatientId());
                inPatientDiagnosisVo.setHospitalCode(medicalPatient.getOrgCode());
                logger.info("inPatientId ={},获取商保住院诊疗信息his入参inPatientDiagnosisVo={}", new Object[]{medicalPatient.getInpatientId(),JsonUtils.toJsonString(inPatientDiagnosisVo)});
                ResCommon<SBInPatientDiagnosisVoResponse> hisfiaceDiagnosisResponse = HisifaceService.getHisifaceClient().getSBInPatientDiagnosis(inPatientDiagnosisVo);
                logger.info("inPatientId ={},获取商保住院诊疗信息his出参 hisfiaceDiagnosisResponse ={}", new Object[]{medicalPatient.getInpatientId(),JsonUtils.toJsonString(hisfiaceDiagnosisResponse)});
                if (!"0".equals(hisfiaceDiagnosisResponse.getResultCode())) {
                    medicalPatient.setDownLoadDiagnosisExceptionMessage(hisfiaceDiagnosisResponse.getResultMessage());
                    medicalPatient.setDownLoadDiagnosisTimes(medicalPatient.getDownLoadDiagnosisTimes() + 1);
                    medicalPatientDao.update(medicalPatient);
                    continue;
                }

                SBInPatientDiagnosisVoResponse sbInPatientDiagnosisVoResponse = hisfiaceDiagnosisResponse.getResult();

                if (sbInPatientDiagnosisVoResponse != null) {
                    MedicalInhospitalDiagnosis medicalInhospitalDiagnosis = buildMedicalInhospitalDiagnosis(sbInPatientDiagnosisVoResponse);
                    medicalInhospitalDiagnosis.setTotalRows(2);
                    medicalInhospitalDiagnosis.setCurrentOffset(2);
                    medicalInhospitalDiagnosis.setOrgCode(medicalPatient.getOrgCode());
                    medicalInhospitalDiagnosis.setCaseNo(medicalPatient.getCaseNo());
                    medicalInhospitalDiagnosis.setMedicalPatientId(medicalPatient.getId());
                    logger.info("inPatientId ={},商保住院诊疗信息入库",medicalPatient.getInpatientId());
                    medicalPatient.setDownLoadDiagnosisTimes(medicalPatient.getDownLoadDiagnosisTimes() + 1);
                    medicalPatient.setDownLoadDiagnosisFlag(new Short("1"));
                    medicalPatientDao.update(medicalPatient);
                    medicalInhospitalDiagnosisDao.insert(medicalInhospitalDiagnosis);
                    logger.info("inPatientId ={},商保住院诊疗信息入库后更新就诊人信息状态",medicalPatient.getInpatientId());
                }
            }
        }
    }

    private MedicalInhospitalDiagnosis buildMedicalInhospitalDiagnosis(SBInPatientDiagnosisVoResponse sbInPatientDiagnosisVoResponse) {
        MedicalInhospitalDiagnosis medicalInhospitalDiagnosis = new MedicalInhospitalDiagnosis();
        medicalInhospitalDiagnosis.setId(PKGenerator.generateId());
        medicalInhospitalDiagnosis.setInDeptName(sbInPatientDiagnosisVoResponse.getInDeptName());
        medicalInhospitalDiagnosis.setInpatientId(sbInPatientDiagnosisVoResponse.getInPatientId());
        medicalInhospitalDiagnosis.setPatId(sbInPatientDiagnosisVoResponse.getPatId());
        medicalInhospitalDiagnosis.setAdmissionNo(sbInPatientDiagnosisVoResponse.getAdmissionNo());
        medicalInhospitalDiagnosis.setInTime(conveterStringToInt(sbInPatientDiagnosisVoResponse.getInTime()));
        medicalInhospitalDiagnosis.setHospitalCode(sbInPatientDiagnosisVoResponse.getHospitalCode());
        medicalInhospitalDiagnosis.setHospitalName(sbInPatientDiagnosisVoResponse.getHospitalName());
        medicalInhospitalDiagnosis.setHospitalType(conveterStringToShort(sbInPatientDiagnosisVoResponse.getHospitalType()));
        medicalInhospitalDiagnosis.setMedicalType(conveterStringToShort(sbInPatientDiagnosisVoResponse.getMedicalType()));
        medicalInhospitalDiagnosis.setHouseDoctorCode(sbInPatientDiagnosisVoResponse.getHouseDoctorCode());
        medicalInhospitalDiagnosis.setHouseDoctorName(sbInPatientDiagnosisVoResponse.getHouseDoctorName());
        medicalInhospitalDiagnosis.setAttendingDoctorCode(sbInPatientDiagnosisVoResponse.getAttendingDoctorCode());
        medicalInhospitalDiagnosis.setAttendingDoctorName(sbInPatientDiagnosisVoResponse.getAttendingDoctorName());
        medicalInhospitalDiagnosis.setChiefDoctorCode(sbInPatientDiagnosisVoResponse.getChiefDoctorCode());
        medicalInhospitalDiagnosis.setChiefDoctorName(sbInPatientDiagnosisVoResponse.getChiefDoctorName());
        medicalInhospitalDiagnosis.setInPatientTime(sbInPatientDiagnosisVoResponse.getInPatientTime());
        medicalInhospitalDiagnosis.setInDeptTime(sbInPatientDiagnosisVoResponse.getInDeptTime());
        medicalInhospitalDiagnosis.setInMethod(sbInPatientDiagnosisVoResponse.getInMethod());
        medicalInhospitalDiagnosis.setInReason(sbInPatientDiagnosisVoResponse.getInReason());
        medicalInhospitalDiagnosis.setEndemicArea(sbInPatientDiagnosisVoResponse.getEndemicArea());
        medicalInhospitalDiagnosis.setInDeptCode(sbInPatientDiagnosisVoResponse.getInDeptCode());
        medicalInhospitalDiagnosis.setBedNo(sbInPatientDiagnosisVoResponse.getBedNo());
        medicalInhospitalDiagnosis.setOutDeptName(sbInPatientDiagnosisVoResponse.getOutDeptName());
        medicalInhospitalDiagnosis.setOutDeptCode(sbInPatientDiagnosisVoResponse.getOutDeptCode());
        medicalInhospitalDiagnosis.setOutPatientTime(trimValue(sbInPatientDiagnosisVoResponse.getOutPatientTime()));
        medicalInhospitalDiagnosis.setDeadTime(sbInPatientDiagnosisVoResponse.getDeadTime());
        medicalInhospitalDiagnosis.setDeadReason(sbInPatientDiagnosisVoResponse.getDeadReason());
        medicalInhospitalDiagnosis.setInDiagnosisCode(sbInPatientDiagnosisVoResponse.getInDiagnosisCode());
        medicalInhospitalDiagnosis.setInDiagnosisName(sbInPatientDiagnosisVoResponse.getInDiagnosisName());
        medicalInhospitalDiagnosis.setInDiagnosisDoctorCode(sbInPatientDiagnosisVoResponse.getInDiagnosisDoctorCode());
        medicalInhospitalDiagnosis.setInMedicalDiagnosisName(sbInPatientDiagnosisVoResponse.getInMedicalDiagnosisName());
        medicalInhospitalDiagnosis.setMedicalHistoryStatement(sbInPatientDiagnosisVoResponse.getMedicalHistoryStatement());
        medicalInhospitalDiagnosis.setHistoryPresentIllness(sbInPatientDiagnosisVoResponse.getHistoryPresentIllness());
        medicalInhospitalDiagnosis.setPastHistory(sbInPatientDiagnosisVoResponse.getPastHistory());
        medicalInhospitalDiagnosis.setMaritalHistory(sbInPatientDiagnosisVoResponse.getMaritalHistory());
        medicalInhospitalDiagnosis.setPersonalHistory(sbInPatientDiagnosisVoResponse.getPersonalHistory());
        medicalInhospitalDiagnosis.setFamilyHistory(sbInPatientDiagnosisVoResponse.getFamilyHistory());
        medicalInhospitalDiagnosis.setAllergyHistory(sbInPatientDiagnosisVoResponse.getAllergyHistory());
        medicalInhospitalDiagnosis.setMenstruationHistory(sbInPatientDiagnosisVoResponse.getMenstruationHistory());
        medicalInhospitalDiagnosis.setPhysicalExaminatio(sbInPatientDiagnosisVoResponse.getPhysicalExamination());
        medicalInhospitalDiagnosis.setSpecialistExamination(sbInPatientDiagnosisVoResponse.getSpecialistExamination());
        medicalInhospitalDiagnosis.setAuxiliaryExamination(sbInPatientDiagnosisVoResponse.getAuxiliaryExamination());
        medicalInhospitalDiagnosis.setTreatreCommend(sbInPatientDiagnosisVoResponse.getTreatRecommend());
        medicalInhospitalDiagnosis.setOutReason(conveterStringToShort(sbInPatientDiagnosisVoResponse.getOutReason()));
        medicalInhospitalDiagnosis.setOutDiseaseCode(sbInPatientDiagnosisVoResponse.getOutDiseaseCode());
        medicalInhospitalDiagnosis.setOutDiseaseName(sbInPatientDiagnosisVoResponse.getOutDiseaseName());
        medicalInhospitalDiagnosis.setOutAdvice(sbInPatientDiagnosisVoResponse.getOutAdvice());
        medicalInhospitalDiagnosis.setOutMedicalDiagnosisCode(sbInPatientDiagnosisVoResponse.getOutMedicalDiagnosisCode());
        medicalInhospitalDiagnosis.setOutMedicalDiagnosisName(sbInPatientDiagnosisVoResponse.getOutMedicalDiagnosisName());
        medicalInhospitalDiagnosis.setComplication(sbInPatientDiagnosisVoResponse.getComplication());
        medicalInhospitalDiagnosis.setInIcuTime(sbInPatientDiagnosisVoResponse.getInIcuTime());
        medicalInhospitalDiagnosis.setOutIcuTime(sbInPatientDiagnosisVoResponse.getOutIcuTime());
        medicalInhospitalDiagnosis.setSecondDiagnosisCode1(sbInPatientDiagnosisVoResponse.getSecondDiagnosisCode1());
        medicalInhospitalDiagnosis.setSecondDiagnosisName1(sbInPatientDiagnosisVoResponse.getSecondDiagnosisName1());
        medicalInhospitalDiagnosis.setSecondDiagnosisCode2(sbInPatientDiagnosisVoResponse.getSecondDiagnosisCode2());
        medicalInhospitalDiagnosis.setSecondDiagnosisName2(sbInPatientDiagnosisVoResponse.getSecondDiagnosisName2());
        medicalInhospitalDiagnosis.setSecondDiagnosisCode3(sbInPatientDiagnosisVoResponse.getSecondDiagnosisCode3());
        medicalInhospitalDiagnosis.setSecondDiagnosisName3(sbInPatientDiagnosisVoResponse.getSecondDiagnosisName3());
        medicalInhospitalDiagnosis.setSecondDiagnosisCode4(sbInPatientDiagnosisVoResponse.getSecondDiagnosisCode4());
        medicalInhospitalDiagnosis.setSecondDiagnosisName4(sbInPatientDiagnosisVoResponse.getSecondDiagnosisName4());
        medicalInhospitalDiagnosis.setInDays(conveterStringToShort(sbInPatientDiagnosisVoResponse.getInDays()));
        medicalInhospitalDiagnosis.setElectronicMedicalRecords(sbInPatientDiagnosisVoResponse.getElectronicMedicalRecords());
        medicalInhospitalDiagnosis.setCreatedTime(DateUtils.dateToString(new Date()));
        return medicalInhospitalDiagnosis;
    }

    private static String trimValue(String value) {
        String result = null;
        if (value != null) {
            result = StringUtils.isBlank(value.trim()) ? null : value.trim();
        }
        return result;
    }

    private Short conveterStringToShort(String value) {
        return value == null ? null : Short.valueOf(value);
    }

    private Integer conveterStringToInt(String value) {
        return value == null ? null : Integer.valueOf(value);
    }

}
